package com.proactive.webapp.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.proactive.webapp.dao.ActivityDAO;
import com.proactive.webapp.dao.CardTemplateDAO;
import com.proactive.webapp.dao.MenuDAO;
import com.proactive.webapp.entity.Activity;
import com.proactive.webapp.entity.CardTemplate;
import com.proactive.webapp.entity.Manager;
import com.proactive.webapp.entity.Member;
import com.proactive.webapp.entity.Menu;
import com.proactive.webapp.util.CompressImage;
import com.proactive.webapp.util.DateConversion;
import com.proactive.webapp.util.FileUtil;
import com.proactive.webapp.util.MenuUtil;
import com.proactive.webapp.util.PageCount;

@Controller
public class CardTemplateController {
	ApplicationContext context =  new ClassPathXmlApplicationContext("spring-module.xml");

	@RequestMapping(value = "/previewCard", method = RequestMethod.GET)
	public ModelAndView previewCard(HttpSession session, int id) {
		ModelAndView model = new ModelAndView();
		CardTemplateDAO cardTemplateDAO = (CardTemplateDAO)context.getBean("cardTemplateDAO");
		CardTemplate cardTemplate = new CardTemplate();
		cardTemplate.setId(id);
		cardTemplate = cardTemplateDAO.get(cardTemplate);
		if(cardTemplate.getTitle() != null){
			Member loginMember = (Member)session.getAttribute("loginMember");
			List<Menu> menuList = MenuUtil.getList(((MenuDAO)context.getBean("menuDAO")).getList(), 5);
			
			model.addObject("cardTemplate", cardTemplate);
			model.setViewName(loginMember==null?"previewCard2":"previewCard1");
			model.addObject("menuList", menuList);
		}
		else
			model.setViewName("redirect:/error");
		return model;
	}
	
	@RequestMapping(value = "/management/manageCardTemplate", method = RequestMethod.GET)
	public ModelAndView cardTemplateCont(HttpSession session, HttpServletRequest request) {
		ModelAndView model = new ModelAndView();

		Manager loginManager = (Manager)session.getAttribute("loginManager");
		if(loginManager != null){
			CardTemplateDAO cardTemplateDAO = (CardTemplateDAO)context.getBean("cardTemplateDAO");
			List<CardTemplate> cardTemList = new ArrayList<CardTemplate>();
			int pageNow = request.getParameter("p")==null?1:Integer.parseInt(request.getParameter("p"));
			//set pager
			int pageSize = 10;
			int count = cardTemplateDAO.countTotal();
			String pageUrl = "manageCardTemplate";
			String pageEndUrl1 = "";
			PageCount pageCount = new PageCount(pageNow, pageSize, count, pageUrl, pageEndUrl1);
			pageCount.calculate();
			cardTemList = cardTemplateDAO.getList(pageCount.getStart(), pageSize);
			//set model
			model.addObject("page", pageCount);
			model.addObject("cardTemList", cardTemList);
			
			model.setViewName("management/manageCardTemplate");
		}
		else
			model.setViewName("redirect:/management/login");
		
		return model;
	}
	
	@RequestMapping(value = "/management/delCardTemplate", method = RequestMethod.POST)
	public ModelAndView delCardTemplate(HttpServletRequest request, HttpSession session) {

		ModelAndView model = new ModelAndView();
		Manager loginManager = (Manager)session.getAttribute("loginManager");
		if(loginManager != null){
			String id = request.getParameter("id")==null?"":request.getParameter("id");
			CardTemplateDAO cardTemplateDAO = (CardTemplateDAO)context.getBean("cardTemplateDAO");
			CardTemplate cardTemplate = new CardTemplate();
			cardTemplate.setId(Integer.parseInt(id));
			cardTemplateDAO.delete(cardTemplate);
			model.setViewName("redirect:/management/manageCardTemplate");
		}
		else
			model.setViewName("redirect:/management/login");
		return model;
	}
	
	@RequestMapping(value = "/management/addCardTemplateCont", method = RequestMethod.GET)
	public ModelAndView addCardTemplateCont(HttpSession session) {
		ModelAndView model = new ModelAndView();
		Manager loginManager = (Manager)session.getAttribute("loginManager");
		if(loginManager != null){
			ActivityDAO activityDAO = (ActivityDAO)context.getBean("activityDAO");
			List<Activity> activityList = new ArrayList<Activity>();
			activityList = activityDAO.getActivityList();
			model.addObject("activityList", activityList);
			
			model.setViewName("management/addCardTemplate");
		}
		else
			model.setViewName("redirect:/management/login");
		return model;
	}
	
	@RequestMapping(value = "/management/addCardTemplate", method = RequestMethod.POST)
	public ModelAndView addCardTemplate(@ModelAttribute CardTemplate cardTemplate, HttpSession session) {

		ModelAndView model = new ModelAndView();
		Manager loginManager = (Manager)session.getAttribute("loginManager");
		if(loginManager != null){
			String imagePath = session.getServletContext().getRealPath("resources/image/activity/template");
			String html1Path = session.getServletContext().getRealPath("resources/file/activity/template");
			String html2Path = session.getServletContext().getRealPath("resources/file/activity/template");
			DateConversion dateConversion = new DateConversion();
			Date now = new Date();
			if(cardTemplate.getImage().getSize() > 0){
				FileUtil fileUtil = new FileUtil(cardTemplate.getImage().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) + "." + fileUtil.getFileType();
				File targetFile = new File(imagePath, newFileName);
				if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	cardTemplate.getImage().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        cardTemplate.setImagePath("resources/image/activity/template/"+newFileName);
		        if(!fileUtil.getFileType().equals("gif")){
		    		CompressImage compressImage = new CompressImage();
		        	compressImage.compress(imagePath+"/", newFileName, 0, 0, false);
		        }
			}
			
			if(cardTemplate.getHtml1().getSize() > 0){
				FileUtil fileUtil = new FileUtil(cardTemplate.getHtml1().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ 1 + "." + fileUtil.getFileType();
				File targetFile = new File(html1Path, newFileName);
				if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	cardTemplate.getHtml1().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        cardTemplate.setHtml1Path("resources/file/activity/template/"+newFileName);
			}
			
			if(cardTemplate.getHtml2().getSize() > 0){
				FileUtil fileUtil = new FileUtil(cardTemplate.getHtml2().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ 2 + "." + fileUtil.getFileType();
				File targetFile = new File(html2Path, newFileName);
				if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	cardTemplate.getHtml2().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        cardTemplate.setHtml2Path("resources/file/activity/template/"+newFileName);
			}
			
			cardTemplate.setStatus(cardTemplate.getStatus()==2?2:1);
			
			model.setViewName("redirect:/management/manageCardTemplate");
			CardTemplateDAO cardTemplateDAO = (CardTemplateDAO)context.getBean("cardTemplateDAO");
			cardTemplateDAO.insert(cardTemplate);
		}
		else
			model.setViewName("redirect:/management/login");
		return model;
	}
	
	@RequestMapping(value = "/management/modiCardTemplateCont", method = RequestMethod.GET)
	public ModelAndView modiCardTemplateCont(HttpSession session, int id) {
		ModelAndView model = new ModelAndView();
		Manager loginManager = (Manager)session.getAttribute("loginManager");
		if(loginManager != null){
			CardTemplateDAO cardTemplateDAO = (CardTemplateDAO)context.getBean("cardTemplateDAO");
			CardTemplate cardTemplate = new CardTemplate();
			cardTemplate.setId(id);
			cardTemplate = cardTemplateDAO.get(cardTemplate);
			ActivityDAO activityDAO = (ActivityDAO)context.getBean("activityDAO");
			List<Activity> activityList = new ArrayList<Activity>();
			activityList = activityDAO.getActivityList();
			for (int i=0; i<activityList.size(); i++) {
				Activity activity = activityList.get(i);
				if(cardTemplate.getAid() == activity.getId())
					activityList.get(i).setSelected("selected");
				
			}
			model.addObject("cardTemplate", cardTemplate);
			model.addObject("activityList", activityList);
			
			model.setViewName("management/modiCardTemplate");
		}
		else
			model.setViewName("redirect:/management/login");
		
		
		return model;
	}
	
	@RequestMapping(value = "/management/modiCardTemplate", method = RequestMethod.POST)
	public ModelAndView modiCardTemplate(@ModelAttribute CardTemplate cardTemplate, HttpSession session) {
		
		ModelAndView model = new ModelAndView();
		Manager loginManager = (Manager)session.getAttribute("loginManager");
		if(loginManager != null){
			String path = session.getServletContext().getRealPath("/");
			String imagePath = session.getServletContext().getRealPath("resources/image/activity/template");
			String html1Path = session.getServletContext().getRealPath("resources/file/activity/template");
			String html2Path = session.getServletContext().getRealPath("resources/file/activity/template");

			CardTemplateDAO cardTemplateDAO = (CardTemplateDAO)context.getBean("cardTemplateDAO");
			CardTemplate oldCardTemplate = new CardTemplate();
			oldCardTemplate.setId(cardTemplate.getId());
			oldCardTemplate = cardTemplateDAO.get(oldCardTemplate);

			DateConversion dateConversion = new DateConversion();
			Date now = new Date();
			
			if(cardTemplate.getImage().getSize() > 0){
				FileUtil fileUtil = new FileUtil(cardTemplate.getImage().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) + "." + fileUtil.getFileType();
				File targetFile = new File(imagePath, newFileName);
				if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	cardTemplate.getImage().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        
		        if(!oldCardTemplate.getImagePath().equals("")){
		        	File oldFile = new File(path+oldCardTemplate.getImagePath());
		        	oldFile.delete();
		        }
		        cardTemplate.setImagePath("resources/image/activity/template/"+newFileName);
		        
		        if(!fileUtil.getFileType().equals("gif")){
		    		CompressImage compressImage = new CompressImage();
		        	compressImage.compress(imagePath+"/", newFileName, 0, 0, false);
		        }
			}
			else
				cardTemplate.setImagePath(oldCardTemplate.getImagePath());
			
			if(cardTemplate.getHtml1().getSize() > 0){
				FileUtil fileUtil = new FileUtil(cardTemplate.getHtml1().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ 1 + "." + fileUtil.getFileType();
				File targetFile = new File(html1Path, newFileName);
				if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	cardTemplate.getHtml1().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        
		        if(!oldCardTemplate.getHtml1Path().equals("")){
			        File oldFile = new File(path+oldCardTemplate.getHtml1Path());
		        	oldFile.delete();
		        }
		        cardTemplate.setHtml1Path("resources/file/activity/template/"+newFileName);
			}
			else
				cardTemplate.setHtml1Path(oldCardTemplate.getHtml1Path());

			if(cardTemplate.getHtml2().getSize() > 0){
				FileUtil fileUtil = new FileUtil(cardTemplate.getHtml2().getOriginalFilename());
				String newFileName = dateConversion.ConversionYMDHMS2(now) +"_"+ 2 + "." + fileUtil.getFileType();
				File targetFile = new File(html2Path, newFileName);
				if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }
		        try {
		        	cardTemplate.getHtml2().transferTo(targetFile);
		        } catch (Exception e) {
		            e.printStackTrace();
		        }
		        
		        if(!oldCardTemplate.getHtml2Path().equals("")){
			        File oldFile = new File(path+oldCardTemplate.getHtml2Path());
		        	oldFile.delete();
		        }
		        cardTemplate.setHtml2Path("resources/file/activity/template/"+newFileName);
			}
			else
				cardTemplate.setHtml2Path(oldCardTemplate.getHtml2Path());		


			cardTemplate.setStatus(cardTemplate.getStatus()==2?2:1);
			cardTemplateDAO.update(cardTemplate);
			
			model.setViewName("redirect:/management/manageCardTemplate");
		}
		else
			model.setViewName("redirect:/management/login");
		
		
		return model;
		
	}
}
